import tkinter as tk
from tkinter import Menu, messagebox, simpledialog
import random
import os
import time
from PIL import Image, ImageTk, ImageSequence
import sys
import glob

class DesktopPet:
    def __init__(self, master):
        self.master = master
        self.master.title("桌面宠物")
        self.master.geometry("100x100")
        self.master.attributes("-topmost", True)  # 窗口置顶
        self.master.overrideredirect(True)  # 去掉窗口边框
        self.master.wm_attributes("-transparentcolor", "white")  # 设置白色为透明色
        
        # 初始化变量
        self.x, self.y = 0, 0
        self.dragging = False
        self.animation_frames = []
        self.current_frame = 0
        self.is_moving = False
        self.move_direction = None
        self.animation_speed = 100  # 动画速度(毫秒)
        self.movement_speed = 5  # 移动速度
        self.screen_width = self.master.winfo_screenwidth()
        self.screen_height = self.master.winfo_screenheight()
        self.is_animation_playing = False  # 是否正在自动播放动画
        
        # 初始位置设置在屏幕中间
        self.master.geometry(f"+{self.screen_width//2}+{self.screen_height//2}")
        
        # 创建标签用于显示宠物
        self.pet_label = tk.Label(self.master, bg="white")
        self.pet_label.pack()
        
        # 加载默认GIF动画
        self.load_default_animation()
        
        # 绑定事件
        self.pet_label.bind("<Button-1>", self.on_click)
        self.pet_label.bind("<ButtonRelease-1>", self.stop_drag)
        self.pet_label.bind("<B1-Motion>", self.on_drag)
        self.pet_label.bind("<Button-3>", self.show_menu)  # 右键菜单
        
        # 随机行为
        self.master.after(random.randint(5000, 10000), self.random_action)
        
        # 显示第一帧
        if self.animation_frames:
            self.pet_label.config(image=self.animation_frames[0])
        
        # 启动动画更新
        self.update_pet()
    
    def load_default_animation(self):
        """加载默认动画"""
        # 创建images文件夹和默认图片
        if not os.path.exists("images"):
            os.makedirs("images")
            # 创建一个空的.gitkeep文件以保留目录
            with open(os.path.join("images", ".gitkeep"), "w") as f:
                pass
            print("已创建images文件夹，请在里面放入GIF动画文件")
            
            # 在没有图片的情况下创建一个简单的默认图像
            self.animation_frames = []
            for i in range(2):
                img = tk.PhotoImage(width=64, height=64)
                for x in range(64):
                    for y in range(64):
                        if (x-32)**2 + (y-32)**2 <= 30**2:
                            color = "#ffcc00" if i == 0 else "#ffaa00"
                            img.put(color, (x, y))
                self.animation_frames.append(img)
            return
            
        # 尝试加载images文件夹中的所有gif
        gif_files = [f for f in os.listdir("images") if f.lower().endswith('.gif')]
        if gif_files:
            try:
                self.load_gif(os.path.join("images", random.choice(gif_files)))
            except Exception as e:
                print(f"加载GIF出错: {e}")
                # 加载失败时创建默认图像
                self.animation_frames = [tk.PhotoImage(data="R0lGODlhQABAAKECAAAAAP///wAAAAAAACH5BAEKAAIALAAAAABAAEAAAAJihI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is1qt9yu9wsOi8fksvmMTqvX7Lb7DY/L5/S6/Y7P6/f8vv8vKwA7")]
        else:
            print("在images文件夹中未找到GIF文件，使用默认图像")
            self.animation_frames = [tk.PhotoImage(data="R0lGODlhQABAAKECAAAAAP///wAAAAAAACH5BAEKAAIALAAAAABAAEAAAAJihI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is1qt9yu9wsOi8fksvmMTqvX7Lb7DY/L5/S6/Y7P6/f8vv8vKwA7")]
    
    def load_gif(self, gif_path):
        """加载GIF动画"""
        self.animation_frames = []
        gif = Image.open(gif_path)
        
        # 遍历GIF帧
        for frame in ImageSequence.Iterator(gif):
            frame = frame.convert('RGBA')
            photo_image = ImageTk.PhotoImage(frame)
            self.animation_frames.append(photo_image)
    
    def on_click(self, event):
        """处理点击事件：如果是拖动则处理拖动，否则切换到下一帧"""
        # 记录初始位置用于判断是点击还是拖动
        self.dragging = True
        self.drag_start_x = event.x
        self.drag_start_y = event.y
        self.x = event.x
        self.y = event.y
        self.is_moving = False  # 用户拖动时停止随机移动
    
    def stop_drag(self, event):
        """停止拖动，如果没有拖动则视为点击"""
        # 判断是否有明显移动，如果没有则视为点击
        if self.dragging and abs(event.x - self.drag_start_x) < 5 and abs(event.y - self.drag_start_y) < 5:
            # 这是一个点击，切换到下一帧
            self.next_frame()
        
        self.dragging = False
    
    def next_frame(self):
        """切换到下一帧动画"""
        if self.animation_frames:
            self.current_frame = (self.current_frame + 1) % len(self.animation_frames)
            self.pet_label.config(image=self.animation_frames[self.current_frame])
    
    def update_pet(self):
        """更新宠物状态"""
        # 根据当前状态移动宠物
        if self.is_moving:
            self.move_pet()
        
        # 继续循环更新
        self.master.after(self.animation_speed, self.update_pet)
    
    def on_drag(self, event):
        """拖动时的处理"""
        if self.dragging:
            x_pos = self.master.winfo_x() + (event.x - self.x)
            y_pos = self.master.winfo_y() + (event.y - self.y)
            self.master.geometry(f"+{x_pos}+{y_pos}")
    
    def move_pet(self):
        """移动宠物"""
        x_pos = self.master.winfo_x()
        y_pos = self.master.winfo_y()
        
        # 根据移动方向调整位置
        if self.move_direction == "left":
            x_pos -= self.movement_speed
        elif self.move_direction == "right":
            x_pos += self.movement_speed
        elif self.move_direction == "up":
            y_pos -= self.movement_speed
        elif self.move_direction == "down":
            y_pos += self.movement_speed
        elif self.move_direction == "random":
            x_pos += random.randint(-self.movement_speed, self.movement_speed)
            y_pos += random.randint(-self.movement_speed, self.movement_speed)
        
        # 确保宠物不会移出屏幕
        x_pos = max(0, min(self.screen_width - 100, x_pos))
        y_pos = max(0, min(self.screen_height - 100, y_pos))
        
        self.master.geometry(f"+{x_pos}+{y_pos}")
    
    def random_action(self):
        """随机行为"""
        # 随机选择一个行为
        actions = ["move_left", "move_right", "move_up", "move_down", 
                  "move_random", "stop", "sleep"]
        action = random.choice(actions)
        
        if action == "move_left":
            self.is_moving = True
            self.move_direction = "left"
        elif action == "move_right":
            self.is_moving = True
            self.move_direction = "right"
        elif action == "move_up":
            self.is_moving = True
            self.move_direction = "up"
        elif action == "move_down":
            self.is_moving = True
            self.move_direction = "down"
        elif action == "move_random":
            self.is_moving = True
            self.move_direction = "random"
        elif action == "stop":
            self.is_moving = False
        elif action == "sleep":
            self.is_moving = False
            # 这里可以切换到睡眠动画
        
        # 设置下一次随机行为的时间
        self.master.after(random.randint(3000, 8000), self.random_action)
    
    def show_menu(self, event):
        """显示右键菜单"""
        menu = Menu(self.master, tearoff=0)
        menu.add_command(label="换肤", command=self.change_skin)
        menu.add_command(label="设置", command=self.show_settings)
        menu.add_command(label="图片合成GIF", command=self.combine_images_to_gif)
        menu.add_separator()
        menu.add_command(label="退出", command=self.master.quit)
        menu.post(event.x_root, event.y_root)
    
    def change_skin(self):
        """更换皮肤功能"""
        # 获取images文件夹中的所有gif
        if not os.path.exists("images"):
            os.makedirs("images")
            tk.messagebox.showinfo("提示", "请在images文件夹中放入GIF动画文件")
            return
            
        gif_files = [f for f in os.listdir("images") if f.lower().endswith('.gif')]
        if not gif_files:
            tk.messagebox.showinfo("提示", "没有找到GIF文件，请在images文件夹中添加")
            return
            
        # 随机选择一个不同的GIF
        current_gif = None
        if hasattr(self, 'current_gif'):
            current_gif = self.current_gif
            
        new_gif = current_gif
        while new_gif == current_gif and len(gif_files) > 1:
            new_gif = random.choice(gif_files)
            
        try:
            self.load_gif(os.path.join("images", new_gif))
            self.current_gif = new_gif
        except Exception as e:
            tk.messagebox.showerror("错误", f"加载GIF出错: {e}")
    
    def show_settings(self):
        """显示设置对话框"""
        settings_window = tk.Toplevel(self.master)
        settings_window.title("设置")
        settings_window.geometry("300x200")
        settings_window.attributes("-topmost", True)
        
        # 动画速度设置
        tk.Label(settings_window, text="动画速度:").pack(pady=5)
        speed_scale = tk.Scale(settings_window, from_=50, to=200, orient=tk.HORIZONTAL,
                               length=200, sliderlength=20)
        speed_scale.set(self.animation_speed)
        speed_scale.pack()
        
        # 移动速度设置
        tk.Label(settings_window, text="移动速度:").pack(pady=5)
        move_scale = tk.Scale(settings_window, from_=1, to=10, orient=tk.HORIZONTAL,
                             length=200, sliderlength=20)
        move_scale.set(self.movement_speed)
        move_scale.pack()
        
        # 保存按钮
        def save_settings():
            self.animation_speed = speed_scale.get()
            self.movement_speed = move_scale.get()
            settings_window.destroy()
            
        tk.Button(settings_window, text="保存", command=save_settings).pack(pady=10)
    
    def combine_images_to_gif(self):
        """将images目录下的图片合成为GIF"""
        if not os.path.exists("images"):
            os.makedirs("images")
            tk.messagebox.showinfo("提示", "请在images文件夹中放入图片文件")
            return
            
        # 支持的图片格式
        supported_formats = [".png", ".jpg", ".jpeg", ".bmp"]
        image_files = []
        
        # 查找所有支持的图片文件
        for ext in supported_formats:
            image_files.extend(glob.glob(os.path.join("images", f"*{ext}")))
            image_files.extend(glob.glob(os.path.join("images", f"*{ext.upper()}")))
        
        if not image_files:
            tk.messagebox.showinfo("提示", "没有找到支持的图片文件，请在images文件夹中添加PNG、JPG或BMP图片")
            return
            
        # 按文件名排序
        image_files.sort()
        
        # 询问用户GIF文件名和动画速度
        gif_name = simpledialog.askstring("输入", "请输入GIF文件名（不需要.gif后缀）:", 
                                        initialvalue="my_animation")
        if not gif_name:
            return
            
        # 确保文件名不包含.gif
        if gif_name.lower().endswith('.gif'):
            gif_name = gif_name[:-4]
            
        # 询问动画帧延迟（毫秒）- 调整默认值和最大值
        try:
            frame_duration = simpledialog.askinteger("输入", 
                                                  "请输入帧延迟（毫秒，数值越大动画越慢）:\n推荐值：\n- 100-200：正常速度\n- 300-500：较慢\n- 500-2000：非常慢", 
                                                  initialvalue=300, minvalue=10, maxvalue=3000)
            if not frame_duration:
                return
        except:
            tk.messagebox.showerror("错误", "请输入有效的数字")
            return
            
        try:
            # 打开所有图像
            images = []
            for image_file in image_files:
                img = Image.open(image_file)
                # 转换为RGBA以支持透明
                if img.mode != 'RGBA':
                    img = img.convert('RGBA')
                images.append(img)
                
            if not images:
                tk.messagebox.showinfo("提示", "没有有效的图片文件")
                return
                
            # 确保第一张图像存在
            first_img = images[0]
            output_file = os.path.join("images", f"{gif_name}.gif")
            
            # 保存为GIF
            first_img.save(
                output_file,
                save_all=True,
                append_images=images[1:],
                optimize=False,
                duration=frame_duration,
                loop=0,  # 0表示无限循环
                transparency=255
            )
            
            result = tk.messagebox.askyesno(
                "成功", 
                f"GIF动画已成功创建为 {output_file}！\n是否立即切换到这个新动画？"
            )
            
            if result:
                try:
                    self.load_gif(output_file)
                    self.current_gif = f"{gif_name}.gif"
                except Exception as e:
                    tk.messagebox.showerror("错误", f"切换到新GIF时出错: {e}")
                    
        except Exception as e:
            tk.messagebox.showerror("错误", f"创建GIF出错: {e}")

def main():
    root = tk.Tk()
    app = DesktopPet(root)
    root.mainloop()

if __name__ == "__main__":
    main() 